<template>
  <BasicTable @register="registerTable" :rowSelection="rowSelection">
    <template #tableTitle>
      <a-input placeholder="搜索媒体" allowClear style="width: 30%; margin-bottom: 5px; margin-right: 20px; " @pressEnter="handleSearch" />
      <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleOpenGroupModal">新增分组</a-button>
      <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="handleUpload" :accept="fileTypeLimit">上传</j-upload-button>
      <a-dropdown v-if="checkedKeys.length > 0 && !isSelectModel">
        <template #overlay>
          <a-menu>
            <a-menu-item key="1" @click="batchHandleDelete">
              <Icon icon="ant-design:delete-outlined"></Icon>
              删除
            </a-menu-item>
          </a-menu>
        </template>
        <a-button>批量操作
          <Icon icon="mdi:chevron-down"></Icon>
        </a-button>
      </a-dropdown>
    </template>
    <template #action="{ record }">
      <TableAction :actions="getTableAction(record)" />
    </template>

    <template #media="{ record }">
      <div class="media-material">
        <ImagePreview class="material-image-preview" 
          v-if="record.type === MaterialType.IMAGE.type" 
          :image-list="[{src: record.url, width: 80, height: 80}]"
        />

        <MySimpleAudioPlayer 
          v-if="record.type === MaterialType.VOICE.type"
          :audioList="[{url: record.url}]"
          :show-prev-button="false"
          :show-next-button="false"
          :show-playback-rate="false"
          :show-volume-button="false"
          :show-progress-bar="false"
          :isLoop="false"
          @loaded-metadata="({ duration }) => record.duration = duration"
        />
        <span class="media-voice-duration" v-if="record.type === MaterialType.VOICE.type" >
          {{ record.duration ? record.duration : '0.00' }}
        </span>


        <div class="media-material-name">{{ record.name }}</div>
      </div>
    </template>
  </BasicTable>
  <MaterialDrawer @register="registerMaterialDrawer" @success="reload()"/>
</template>
<script lang="ts" name="MaterialList" setup>
import {nextTick, onUnmounted, ref, unref, watchEffect} from 'vue'
import {downloadByOnlineUrl} from '/@/utils/file/download';
import {BasicTable, TableAction} from '/@/components/Table';
import {useDrawer} from '/@/components/Drawer';
import {useMessage} from '/@/hooks/web/useMessage';
import {ImagePreview} from '/@/components/Preview/index';
import {columns, MaterialType, searchFormSchema} from '../material.data';
import {
  batchDeleteMaterial,
  deleteMaterial,
  pageMaterial,
  saveOrUpdateMaterial
} from '../material.api';
import {useListPage} from '/@/hooks/system/useListPage'
import {propTypes} from '/@/utils/propTypes';
import {uploadApi} from '/@/api/sys/upload'
import {getFileConfig} from '/@/views/infra/file/conf/fileConfig.api'
import {UploadBizType} from '/@/enums/uploadEnum';
import MaterialDrawer from './MaterialDrawer.vue';
import MySimpleAudioPlayer from '/@/components/My/MySimpleAudioPlayer.vue'
import {Icon} from '/@/components/Icon'

const [registerMaterialDrawer, { openDrawer: openMaterial }] = useDrawer();
const { createMessage } = useMessage();
const emit = defineEmits(['open-group', 'update:value', 'select-change']);

const props = defineProps({
  groupId: propTypes.string.def(undefined),
  isSelectModel: propTypes.bool.def(false),
  selectCount: propTypes.number.def(-1), // -1不限制
  // 素材类型
  materialType: propTypes.string.def(MaterialType.IMAGE.name),
});

const fileTypeLimit = ref('*')
const searchParams = ref<any>({})
// 列表页面公共参数、方法
const { prefixCls, tableContext } = useListPage({
  designScope: 'material-list',
  tableProps: {
    api: pageMaterial,
    beforeFetch: (params) => {
      for (const key in searchParams.value) {
        params[key] = searchParams.value[key]
      }
      params.groupId = unref(props.groupId)
      params.type = unref(props.materialType)
    },
    showIndexColumn: false,
    striped: false,
    columns: columns,
    bordered: false,
    actionColumn: {
      width: 140,
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
    immediate: false,
    showTableSetting: false,
    useSearchForm: false,
    formConfig: {
      showSubmitButton: false,
      showResetButton: false,
      schemas: searchFormSchema
    },
  }
})
const checkedKeys = ref<Array<string | number>>([]);

onUnmounted(() => {
  console.log('onUnmounted-props', unref(props));
})

const [registerTable, { reload, clearSelectedRowKeys, getSelectRows }, { }] = tableContext;

watchEffect(() => {
  if (props.groupId) {
    nextTick(() => {
      clearSelectedRowKeys()
      reload()
    })
  }

  if (props.materialType) {
    nextTick(() => {
      initFileLimitType()
    })
  }
});

const initFileLimitType = async () => {
  if (props.materialType) {
    const data = await getFileConfig({bizType: getUploadBizType()})
    fileTypeLimit.value = !data.fileTypeLimit || data.fileTypeLimit === '' ? '*' : data.fileTypeLimit
  }
}
const getUploadBizType = () => {
  if ('image' === props.materialType) {
    return UploadBizType.GENERAL_IMAGE
  }
  if ('video' === props.materialType) {
    return UploadBizType.GENERAL_VIDEO
  }
  if ('voice' === props.materialType) {
    return UploadBizType.GENERAL_VOICE
  }
}
const handleOpenGroupModal = () => {
  console.log('materialType', unref(props.materialType));
  
  emit('open-group', unref(props.materialType))
}

/**
 * 选择列配置
 */
 const rowSelection = {
  type: props.selectCount === 1 ? 'radio' : 'checkbox', // 为 radio 是单选
  columnWidth: 50,
  selectedRowKeys: checkedKeys,
  onChange: onSelectChange
}

/**
 * 选择事件
 */
 function onSelectChange(selectedRowKeys: (string | number)[]) {
  checkedKeys.value = selectedRowKeys;
  console.log('selectedRowKeys', selectedRowKeys);
  emit('select-change', getSelectRows());
}

const handleUpload = async (data) => {
  if (!data.file) {
    return
  }
  console.log('upload: ', data);
  createMessage.loading({
    content: `正在上传...`,
    key: 'upload_material',
    duration: 0,
  });

  try {
    // 上传文件
    const result = await uploadApi({ 
      name: 'file', file: data.file, data:{
      bizType: getUploadBizType()
    }}, (e) => {
      // console.log(e);
    }, true)
    console.log('upload result: ', result);
    
    // 开始保存素材记录
    const materialForm = {
      url: result.data,
      type: props.materialType,
      groupId: props.groupId,
      name: data.file.name,
      size: data.file.size / 1000
    }
    console.log('materialForm', materialForm);
    await saveOrUpdateMaterial(materialForm, false)
    
    createMessage.success({
      content: `上传成功`,
      key: 'upload_material',
      duration: 2,
    });
    reload()
  } catch(e) {
    createMessage.error({
      content: `上传失败`,
      key: 'upload_material',
      duration: 2,
    });
  }
}

const handleSearch = (e) => {
  const keyWord = e.target.value
  searchParams.value.name = keyWord
  console.log('search keyword: ', keyWord);
  reload()
}

/**
 * 编辑
 */
function handleEdit(record) {
  openMaterial(true, {
    materialType: props.materialType,
    fileTypeLimit: fileTypeLimit.value,
    record,
    isUpdate: true,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteMaterial({ id: record.id }, reload);
}
/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDeleteMaterial({ ids: checkedKeys.value }, reload);
}

const handleDownload = (record) => {
  downloadByOnlineUrl(record.url, record.name)
}

/**
 * 操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
    },
    {
      label: '下载',
      onClick: handleDownload.bind(null, record),
    },
    {
      label: '删除',
      color: 'error',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
      }
    }
  ]
}

defineExpose({ reload })

</script>

<style lang="less">
.media-material {
  display: flex;
  align-items: center; 
}
.media-material-name {
  margin-left: 10px;
}
.material-image-preview {
  img {
    width: 80px !important;
    height: 80px !important;
  }
}

.media-voice-duration {
  margin-left: -10px;
  margin-right: 5px;
}
</style>
